package com.cdwang.speaklib;

import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.widget.Toast;

import java.util.Locale;

/**
 * copyright (C), 2022, 运达科技有限公司
 * fileName SpeakUtils
 *
 * @author 王玺权
 * date 2022-10-25 10:08
 * description 语音转换工具类
 * history
 */
public enum  SpeakUtils {
    /**
     * 初始化
     */
    INSTANCE;
    private TextToSpeech textToSpeech=null;
    public void init(Context context){
        textToSpeech=new TextToSpeech(context, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS){
                    int result = textToSpeech.setLanguage(Locale.CHINA);
                    if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){
                        Toast.makeText(context, "数据丢失或不支持", Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Log.e("错误代码",status+"");
                    Toast.makeText(context, "初始化错误"+status, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 开始朗读 maxSize = 4000
     * @param text
     */
    public void read(String text){
//        if (textToSpeech != null && !textToSpeech.isSpeaking()) {
        if (textToSpeech != null ) {
            // 设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
            textToSpeech.setPitch(0.8f);
            //设定语速 ，默认1.0正常语速
            textToSpeech.setSpeechRate(1.0f);
            //朗读，注意这里三个参数的added in API level 4   四个参数的added in API level 21
            Bundle bundle = new Bundle();
            bundle.putInt(TextToSpeech.Engine.KEY_PARAM_STREAM, AudioManager.STREAM_NOTIFICATION);//设置音频通道
            textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, bundle,"1");
        }
    }

    /**
     * 暂停朗读
     */
    public void stop(){
        // 不管是否正在朗读TTS都被打断
        textToSpeech.stop();
        // 关闭，释放资源
        textToSpeech.shutdown();
    }

    /**
     * 销毁
     */
    public void destory(){
        if (textToSpeech != null) {
            textToSpeech.stop();
            textToSpeech.shutdown();
            textToSpeech = null;
        }
    }


}
